#!/bin/bash

set -eu

GROUP_IN=${GROUP_IN:-}
USER_IN=${USER_IN:-}
DEFAULT_PASS=${DEFAULT_PASS:-P@88w0rd}

mkdir -p /inituser
: > /inituser/group.txt
: > /inituser/passwd.txt
: > /inituser/shadow.txt

# 收集“组→成员”映射
declare -A GROUP_MEMS        # 内容将是  gid->"user1,user2"
for u in $USER_IN; do
  [[ -z "$u" ]] && continue
  IFS=: read -r un _ uid gids _ _ <<<"$u"
  for g in ${gids//,/ }; do
    # 把用户加入该 gid 的成员列表
    GROUP_MEMS[$g]="${GROUP_MEMS[$g]:-}${GROUP_MEMS[$g]:+,}${un}"
  done
done

# 记录用户声明的所有 gid（含主组+附加组）
declare -A USER_GIDS               # gid -> 1
for u in $USER_IN; do
  [[ -z "$u" ]] && continue
  IFS=: read -r un _ uid gids _ _ <<<"$u"
  for g in ${gids//,/ }; do
    USER_GIDS[$g]=1
  done
done

declare -A PRINTED_GIDS
# 写用户显式声明的组（GROUP_IN）
for g in $GROUP_IN; do
  [[ -z "$g" ]] && continue
  IFS=: read -r gn gid <<<"$g"
  members=${GROUP_MEMS[$gid]:-}
  echo "${gn}:x:${gid}:${members}" >> /inituser/group.txt
  # 标记已输出
  PRINTED_GIDS[$gid]=1
done

# 补全缺失组（用户在 gids 里提到，但 GROUP_IN 没出现）
for gid in "${!USER_GIDS[@]}"; do
  [[ ${PRINTED_GIDS[$gid]:-} ]] && continue   # 已输出过，跳过
  # 自动生成与用户同名、同 gid 的组
  # 组名 = 第一个用到该 gid 的用户名（可自定义）
  for u in $USER_IN; do
    IFS=: read -r un _ uid gids _ _ <<<"$u"
    [[ " ${gids//,/ } " =~ " $gid " ]] || continue
    auto_gn=$un
    break
  done
  members=${GROUP_MEMS[$gid]:-}
  echo "${auto_gn}:x:${gid}:${members}" >> /inituser/group.txt
done

# 写出用户行（主组用第一个 gid）
for u in $USER_IN; do
  [[ -z "$u" ]] && continue
  IFS=: read -r un upw uid gids home shell <<<"$u"
  [[ -z "$upw" ]] && upw="$DEFAULT_PASS"
  main_gid=${gids%%,*}

  # ---- 生成 SHA-512 密码哈希 ----
  salt=$(tr -dc 'A-Za-z0-9' </dev/urandom | head -c 16)
  # $6$salt$encrypted   (SHA-512)
  pwd_hash=$(perl -e 'print crypt($ARGV[0], "\$6\$" . $ARGV[1] . "\$")' "$upw" "$salt")

  echo "${un}:x:${uid}:${main_gid}::${home:-/home/${un}}:${shell:-/bin/bash}" >> /inituser/passwd.txt
  echo "${un}:${pwd_hash}:$(($(date +%s)/86400)):0:99999:7:::" >> /inituser/shadow.txt
done

echo -e "This directory is ephemeral and will be lost when the pod exits.\nDo NOT save any data or credentials here." > /inituser/_DO_NOT_WRITE_HERE.readme
